<?php

namespace app\admin\controller\purchase;

use app\admin\controller\purchase\Change;
use app\common\controller\Backend;
use app\common\model\purchase\RetreatGoods;
use app\common\model\purchase\EnterGoods;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\goods\Goods;
use app\common\model\Storehouse;
use app\common\model\supplier\Supplier;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Retreat extends Backend
{
    
    /**
     * Retreat模型对象
     * @var \app\common\model\purchase\Retreat
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\purchase\Retreat;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $this->handlefilter();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['purchaseenter','purchaseorder','storehouse','supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['purchaseenter','purchaseorder','storehouse','supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','createtime','number','collectiontime','explain','operator','company','status','tax']);
                $row->visible(['purchaseenter']);
				$row->getRelation('purchaseenter')->visible(['number']);
				$row->visible(['purchaseorder']);
				$row->getRelation('purchaseorder')->visible(['number']);
				$row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
				$row->visible(['supplier']);
				$row->getRelation('supplier')->visible(['nickname']);
            }
            $list = collection($list)->toArray();
            $status = $this->model->retreat_status();
            foreach ($list as $k=>$v){
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $status[$v['status']];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function detail($ids=null){

        $row = $this->model->find($ids);
        if ($this->request->isAjax()) {
            $status = input('status');
            if($status == 2){
                $this->model->save(array('status'=>5),array('id'=>$ids));
                $type = 2;
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>$type,
                    'createtime'=>time(),
                    'controller'=>'purchase/retreat',
                    'source_id'=>$ids,
                    'source'=>3,
                    'remark'=>'采购退货单',
                    'number'=>$row['number'],
                ));
                $RetreatGoods = new RetreatGoods;
                $RetreatGoods->save(array('status'=>0),array('purchase_retreat_id'=>$ids));
                $this->success('驳回成功');
            }

            $paams = input('row/a');
            foreach ($paams as $v){
                $retreatGoods = new RetreatGoods();
                //总入库量
                $erow = EnterGoods::find($v['purchase_enter_goods_id']);
                $enum = $erow['goods_num'];
                //已入货量
                $tnum = $retreatGoods->where(array('purchase_enter_goods_id'=>$v['purchase_enter_goods_id'],'purchase_enter_id'=>$row['purchase_enter_id'],'goods_id'=>$v['goods_id']))->sum('goods_num');
                //当前量
                $rgrow = $retreatGoods->where(array('id'=>$v['id']))->find();
                if(($enum-$tnum+$rgrow['goods_num']-$v['goods_num'])<0){
                        $this->error('退货数量超过入库数量,总入库数量为'.$enum.'当前最大可入库量为'.($enum-$tnum+$rgrow['goods_num']));
                }
            }
            Db::startTrans();
            try{
                $this->model->save(array('status'=>2),array('id'=>$ids));
                $cost = 0;
                foreach ($paams as $v){
                    $retreatGoods = new RetreatGoods();
                    $retreatGoods->save(array('goods_num'=>$v['goods_num']),array('id'=>$v['id']));
                    $cost+=$v['goods_num']*$v['ht_price'];
                }
//                exit;
                $type = 1;
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>$type,
                    'createtime'=>time(),
                    'controller'=>'purchase/retreat',
                    'source_id'=>$ids,
                    'source'=>3,
                    'remark'=>'采购退货单',
                    'number'=>$row['number'],
                ));

                $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

                $custrow = Supplier::find($row['supplier_id']);
                $ress = Db::name('analysis')->insert(array(
                    'is_income' => 1,
                    'source' => 3,
                    'cost' => $cost,
//                    'admin_id' => session('admin')['id'],
//                    'group_id' => $group['group_id'],
//                    'company' => $group['name'],
                    'admin_id'=>$row['admin_id'],
                    'group_id'=>$row['group_id'],
                    'company'=>$row['company'],
                    'operator'=>$row['operator'],
                    'source_id' => $ids,
                    'obj_id' => $row['supplier_id'],
                    'storehouse_id' => $row['storehouse_id'],
//                    'operator' => session('admin')['nickname'],
                    'controller' => 'purchase/retreat',
                    'settle_name' => $custrow['nickname'],
                    'number' => $row['number'],
                    'createtime' => time(),
                    'explain'=>$row['explain'],//摘要
                ));
                if (!$ress) {
                    throw new Exception('数据异常');
                }
                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'审核成功',
                );
            }catch (\Exception $e) {
                Db::rollback();
            }

            exit;

        }
        $store = new Storehouse();
        $hrow = $store->find($row['storehouse_id']);





        $list = Db::name('purchase_retreat_goods')
            ->field('sg.id,sg.goods_id,sg.goods_num,pg.goods_num as pg_num,sg.unit_price,sg.tax,sg.remark,title,place_origin,number,unit,specs,purchase_enter_goods_id,sg.ht_price')
            ->alias('sg')
            ->where(array('purchase_retreat_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->join('purchase_enter_goods pg','sg.purchase_enter_goods_id = pg.id')
            ->select();
        foreach ($list as $k => $v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$row['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);
        }


        $this->assign('list',$list);
        $this->assign('row',$row);
        $this->assign('hrow',$hrow);

        $arr = explode('/',$_SERVER['REQUEST_URI']);
        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    //采购单审核
    public function examine($ids = null){
        $status = input('status/d',0);

        if(empty($status)){
            $this->error('状态异常22');
        }
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('退货单不存在');
        }
//        if($row['status'] !=1){
//            $this->error('状态异常');
//        }



        Db::startTrans();
        try {
            if($status == 3) {
                $odata['status'] = 3;
//
                //减少库存
                $rgoods = new RetreatGoods();
                $list = $rgoods->where(array('purchase_retreat_id' => $ids))->select();
                $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();


                foreach ($list as $v) {
//                    $goods = new \app\common\model\goods\Goods();
//                    $final_cost = $goods->getcost($v['goods_id'],$row['storehouse_id']);
//
//                    $GoodsHouseStock = new GoodsHouseStock;
//                    $stock = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);

                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
                    if($hgood['stock'] == 0){
                        throw new Exception('库存为0');
                    }


                    if($hgood['stock'] == $v['goods_num']){
                        $balance = 0;
                    }else{
                        $balance = $hgood['balance']-handle_price($v['ht_price'],$v['tax'])*$v['goods_num'];
                    }

                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'采购退货单',
                        'source'=>3,
                        'type_id'=>$row['id'],
//                       'enter_num'=>$v['goods_num'],
                        'out_num'=>$v['goods_num'],
                        'before_num'=>$hgood['stock'],
                        'now_num'=>$hgood['stock']-$v['goods_num'],
                        'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                        'controller'=>'purchase/retreat',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
//                        'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                        'final_cost'=>handle_price($v['ht_price'],$v['tax']), //记录的金额应该是入库的加权单价
                        'bill_cost'=>handle_price($v['ht_price'],$v['tax'])*$v['goods_num'], //记录的金额应该是入库的采购单价
                        'balance'=>$balance, //记录的金额当前库存总额
                    ));
                    $GoodsHouseStock = new GoodsHouseStock;
                    $rr = $GoodsHouseStock->reducestock($v['goods_id'],$row['storehouse_id'],$v['goods_num'],handle_price($v['ht_price'],$v['tax']));
//                    $rr = $GoodsHouseStock->reducestock($v['goods_id'], $row['storehouse_id'], $v['goods_num']);
                    if (!$rr) {
                        $Goods = new Goods;
                        $ginfo = $Goods->find($v['goods_id']);
                        Db::rollback();
                        throw new Exception($ginfo['title'] . '库存异常,请检查');
                    }
                }
            }else{
                $odata['status'] = $status;
            }

            $res = $this->model->save($odata,array('id'=>$ids));
            if(!$res){
                Db::rollback();
                throw new Exception(数据异常);
            }
            Db::commit();
            return  array(
                'code'=>1,
                'msg'=>'审核成功',
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /*
     * 检查财务订单
     * 库存
     */
    public function cancelbill($ids = null){
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        $row = $this->model->find($ids);
        if($row['status'] ==1 || $row['status'] >4){
            $this->error('状态异常');
        }
        $analysis = Db::name('analysis')->where(array(
            'source'=>3,
            'source_id' => $row['id'],
            'storehouse_id' => $row['storehouse_id'],
        ))->find();

        //只有财务数据在待处理的时候 才能处理
        if($analysis['status'] != 1){
            $this->error('财务状态异常,请处理');
        }
        Db::startTrans();
        try {
            $rgoods = new RetreatGoods();
            $list = $rgoods->where(array('purchase_retreat_id' => $ids))->select();

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();


            foreach ($list as $v) {
                $GoodsHouseStock = new GoodsHouseStock;
                $rr = $GoodsHouseStock->addstock($v['goods_id'],$row['storehouse_id'],$v['goods_num'],handle_price($v['ht_price'],$v['tax']),1);
                if (!$rr) {
                    $Goods = new Goods;
                    $ginfo = $Goods->find($v['goods_id']);
                    Db::rollback();
                    throw new Exception($ginfo['title'] . '库存异常,请检查');
                }

                $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();

                Db::name('goods_stock_log')->insert(array(
                    'goods_id'=>$v['goods_id'],
                    'createtime'=>time(),
                    'number'=>$row['number'],
                    'type'=>'采购退货单',
                    'source'=>3,
                    'type_id'=>$row['id'],
                    'enter_num'=>$v['goods_num'],
//                    'out_num'=>$v['goods_num'],
                    'before_num'=>$hgood['stock']-$v['goods_num'],
                    'now_num'=>$hgood['stock'],
                    'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                    'controller'=>'purchase/retreat',
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'company'=>$group['name'],
                    'operator'=>session('admin')['nickname'],
//                        'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                    'final_cost'=>handle_price($v['ht_price'],$v['tax']), //记录的金额应该是入库的加权单价
                    'bill_cost'=>handle_price($v['ht_price'],$v['tax'])*$v['goods_num'], //记录的金额应该是入库的采购单价
                    'balance'=>$hgood['balance'], //记录的金额当前库存总额
                    'is_cancel'=>1,
                ));
            }


            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 3,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'purchase/retreat',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));


            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'purchase/retreat',
                'source_id'=>$ids,
                'source'=>3,
                'remark'=>'采购退货单',
                'number'=>isset($row['number'])?$row['number']:'',
            ));

            //中止财务记录
            $ress = Db::name('analysis')->where(array(
                'id' => $analysis['id']
            ))->update(array('status' => 4));
            if (!$ress) {
                throw new Exception('数据异常');
            }
            //修改本身状态
            $this->model->save(array('status' => 6), array('id' => $ids));
            Db::commit();
            return array(
                'code' => 1,
                'msg' => '成功'
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
}
